package com.xhtt.smart.card.client.code;


import com.xhtt.smart.card.common.msg.bean.MsgClientBean;
import com.xhtt.smart.card.common.constant.Contstants;
import com.xhtt.smart.card.common.util.HexConver;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;


/**
 * @author wangze
 * @date 2018-07-04 15:09.
 **/
public class MessageClientEncoder extends MessageToByteEncoder<MsgClientBean> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, MsgClientBean msg, ByteBuf byteBuf) throws Exception {
        if (msg == null) {
            return;
        }

        try (ByteBufOutputStream writer = new ByteBufOutputStream(byteBuf)) {
            writer.write(new byte[]{ Contstants.FRAME_HEADER});
            //传输码
            writer.write( new byte[]{ msg.getTransferType().getIndex()});
            //功能数
            writer.write( new byte[]{1});
            //功能码
            writer.write(new byte[]{msg.getFunctionType().getCode()} );

            writer.write(new byte[]{HexConver.int8ToByte(msg.getDataLength())}  );

            writer.write(msg.getData());
            //不同类型的数据域是不一样的
            writer.write(HexConver.asciiStringToByte("123ASDFGBQ123456"));
            writer.write(new byte[]{1});
            //TODO 校验码
            writer.write(new byte[]{1});
            writer.write(new byte[]{ Contstants.FRAME_FOOT});

            System.out.println("所有字节总长度:"+writer.buffer().readableBytes());

        }
    }
}
